<template>
  <div class="material-libary">
    <!-- 创建资源 -->
    <div style="padding: 5px">
      <el-button
        style="background-color: #ff9f00; color: #ffffff; border: solid #ff9f00 1px"
        size="small"
        @click="addGroupResource = true"
      >
        添加群发素材
      </el-button>
      <el-button
        style="background-color: #ff9f00; color: #ffffff; border: solid #ff9f00 1px"
        size="small"
        @click="addCircleResource = true"
      >
        添加朋友圈素材
      </el-button>
    </div>

    <!-- 资源列表 -->
    <el-table :data="dataList" stripe height="100%">
      <el-table-column label="素材类型" width="100">
        <template slot-scope="scope">
          <span v-text="tasktypeMap[scope.row.type]"></span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.restype" v-text="restypeMap[scope.row.restype]"></span>
          <span v-else v-text="scope.row.circleType"></span>
        </template>
      </el-table-column>
      <el-table-column label="消息内容">
        <template slot-scope="scope">
          <div
            :class="[
              {
                'chat-link': scope.row.restype === 6
              },
              {
                'chat-app': scope.row.restype === 13
              }
            ]"
            v-html="decodeChat(scope.row)"
          ></div>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remarks" width="100"></el-table-column>

      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <span v-text="$options.filters.transformTime2Minute(scope.row.createTime)"></span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160">
        <template slot-scope="{ row }">
          <el-button :disabled="row.type === 5" size="mini" @click="modifyItem(row)">编辑</el-button>
          <el-button
            style="background-color: #ff9f00; color: #ffffff"
            type="warning"
            size="mini"
            @click="deleteItem(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin: 5px"
      :current-page="currentPage"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="7"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 刷新素材 -->
    <el-button
      style="
        background-color: #ff9f00;
        color: #ffffff;
        border: solid #ff9f00 1px;
        position: absolute;
        bottom: 5px;
        right: 20px;
      "
      size="small"
      @click="queryResourceData"
    >
      刷新素材
    </el-button>

    <!-- 创建群发素材 -->
    <el-dialog
      title="创建群发素材"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      class="add-group-send-dialog"
      :visible.sync="addGroupResource"
    >
      <!-- aside -->
      <ul class="add-reply-aside">
        <li
          v-for="(mt, index) in msgTypes"
          :key="index"
          :class="{ 'li-selected': msgType === mt.type }"
          @click="toggleGroupSendType(mt.type)"
        >
          <i class="fa" :class="mt.icon" aria-hidden="true"></i>
          {{ mt.name }}
        </li>
      </ul>

      <Expression class="qq-expression-2" @expressionContent="modifyContent" />

      <!-- 文本 -->
      <el-input
        v-if="msgType === 'Text'"
        v-model.trim="textContent"
        type="textarea"
        placeholder="请输入内容"
        maxlength="500"
        show-word-limit
        resize="none"
      ></el-input>

      <!-- content -->
      <div v-else class="add-reply-content">
        <!-- 图片 -->
        <template v-if="msgType === 'Picture'">
          <template v-if="!pictureUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiatupian.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addPicture">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加图片</span>
            </label>
            <input
              v-show="false"
              id="addPicture"
              ref="pictureInputRef"
              type="file"
              accept=".jpg, .png, .jpeg"
              @change="chosePicture"
            />
          </template>
          <template v-else>
            <img style="max-width: 400px; max-height: 190px" :src="pictureUrl" alt="图片" />
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="pictureName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deletePicture"></i>
            </div>
          </template>
        </template>
        <!-- 语音 -->
        <template v-else-if="msgType === 'Voice'">
          <template v-if="!voiceUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addVoice">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加语音</span>
            </label>
            <input
              v-show="false"
              id="addVoice"
              ref="voiceInputRef"
              type="file"
              accept=".mp3, .amr"
              @change="choseVoice"
            />
          </template>
          <template v-else>
            <audio style="max-width: 400px; max-height: 190px; margin-top: 60px" :src="voicePlayUrl" controls></audio>
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="voiceName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deleteVoice"></i>
            </div>
          </template>
        </template>
        <!-- 视频 -->
        <template v-else-if="msgType === 'Video'">
          <template v-if="!videoUrl">
            <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
            <label style="cursor: pointer; padding: 5px" for="addPicture">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加视频</span>
            </label>
            <input v-show="false" id="addPicture" ref="videoInputRef" type="file" accept=".mp4" @change="choseVideo" />
          </template>
          <template v-else>
            <video style="max-width: 400px; max-height: 190px" :src="videoUrl" controls></video>
            <div style="display: flex; align-items: center; height: 32px">
              <p style="margin-right: 5px" v-text="videoName"></p>
              <i style="cursor: pointer" class="el-icon-delete" @click="deleteVideo"></i>
            </div>
          </template>
        </template>

        <!-- link -->
        <el-form
          v-else-if="msgType === 'Link'"
          ref="linkDialog"
          :model="linkForm"
          :rules="linkRules"
          label-width="110px"
        >
          <el-form-item v-for="(link, index) in linkForm" :key="'link' + index" :label="linkName[index]" :prop="index">
            <el-input v-model="linkForm[index]" :disabled="index === 'TypeStr'" clearable></el-input>
          </el-form-item>
        </el-form>
        <!-- weapp -->
        <el-form
          v-else-if="msgType === 'WeApp'"
          ref="weappDialog"
          :model="weapp"
          :rules="weappRules"
          label-width="110px"
        >
          <el-form-item v-for="(wa, index) in weapp" :key="'weapp' + index" :label="index" :prop="index">
            <el-input v-model="weapp[index]" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- footer -->
      <span slot="footer">
        <el-input
          v-model="remarks"
          style="width: 540px; margin-left: 30px"
          clearable
          size="small"
          placeholder="请输入备注"
          maxlength="50"
          show-word-limit
        ></el-input>
        <el-button style="margin-left: 10px; color: #999999" size="small" @click="cancleGroupSend">取 消</el-button>
        <el-button
          v-if="modifyRow.id"
          style="background-color: #ff9f00; border: solid #ff9f00 1px"
          type="primary"
          size="small"
          @click="createGroupSend"
        >
          更 新
        </el-button>
        <el-button
          v-else
          style="background-color: #ff9f00; border: solid #ff9f00 1px"
          type="primary"
          size="small"
          @click="createGroupSend"
        >
          创 建
        </el-button>
      </span>
    </el-dialog>

    <!-- 创建朋友圈素材 -->
    <el-dialog
      title="创建朋友圈素材"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      class="create-circle-resource"
      :visible.sync="addCircleResource"
    >
      <!-- 类型 -->
      <ul class="set-circle-type">
        <li
          class="circle-type-item"
          :class="{ 'circle-type-item-select': circleType === 'text' }"
          @click="toggleCircleType('text')"
        >
          <img v-if="circleType === 'text'" src="../../../assets/images/circles/wenben-active.svg" alt="" />
          <img v-else src="../../../assets/images/circles/wenben.svg" alt="" />
          文本
        </li>
        <li
          class="circle-type-item"
          :class="{ 'circle-type-item-select': circleType === 'picture' }"
          @click="toggleCircleType('picture')"
        >
          <img v-if="circleType === 'picture'" src="../../../assets/images/circles/tupian-active.svg" alt="" />
          <img v-else src="../../../assets/images/circles/tupian.svg" alt="" />
          图片
        </li>
        <li
          class="circle-type-item"
          :class="{ 'circle-type-item-select': circleType === 'video' }"
          @click="toggleCircleType('video')"
        >
          <img v-if="circleType === 'video'" src="../../../assets/images/circles/shipin-active.svg" alt="" />
          <img v-else src="../../../assets/images/circles/shipin.svg" alt="" />
          视频
        </li>
        <li
          class="circle-type-item"
          :class="{ 'circle-type-item-select': circleType === 'link' }"
          @click="toggleCircleType('link')"
        >
          <img v-if="circleType === 'link'" src="../../../assets/images/circles/lianjie-active.svg" alt="" />
          <img v-else src="../../../assets/images/circles/lianjie.svg" alt="" />
          链接
        </li>
      </ul>

      <!-- 设置发送内容 -->
      <div class="set-send-content scroll">
        <!-- 文本 -->
        <el-input
          v-model="textContent"
          type="textarea"
          placeholder="这一刻的想法..."
          style="height: auto; width: 100%"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 6, maxRows: 6 }"
          resize="none"
        ></el-input>
        <Expression class="qq-expression" @expressionContent="modifyContent" />

        <!-- 上传|展示 图片 -->
        <div v-if="circleType === 'picture'" class="add-pictures">
          <img
            v-if="imagesList.length === 0"
            style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%)"
            src="../../../assets/images/circles/tianjiatupian.png"
            alt=""
          />
          <!-- 图片 -->
          <el-upload
            class="set-image-ulrs"
            :action="actionUrl"
            list-type="picture-card"
            accept=".jpg, .png, .jpeg"
            :class="{ hide: hideUpload }"
            :multiple="true"
            :limit="9"
            :file-list="imagesList"
            :data="upData"
            :show-file-list="showFileList"
            :on-change="handleImageChange"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleImageRemove"
            :on-exceed="handleImageExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>

        <!-- 上传|展示 视频 -->
        <div v-else-if="circleType === 'video'" class="add-video">
          <template v-if="!videoUrl">
            <img src="../../../assets/images/circles/tianjiashipin.png" alt="" />
            <label class="add-video-label" for="addVideo">
              <i class="el-icon-plus"></i>
              <span style="color: #576c95; font-size: 14px">添加视频</span>
            </label>
            <input
              v-show="false"
              id="addVideo"
              ref="videoInputRef"
              type="file"
              accept=".mp4"
              @change="choseCircleVideo"
            />
          </template>
          <template v-else>
            <video :src="videoUrl" controls></video>
            <div class="video-name-delete">
              <p style="margin-right: 5px" v-text="videoName"></p>
              <i class="el-icon-delete" @click="deleteCircleVideo"></i>
            </div>
          </template>
        </div>

        <!-- 设置链接 -->
        <template v-if="circleType === 'link'">
          <!-- 图片的url -->
          <div class="set-circle-link">
            <span class="base-tips">请输入图片地址</span>
            <el-input
              v-model="linkImg"
              placeholder="请输入图片地址"
              maxlength="200"
              minlength="12"
              clearable
            ></el-input>
          </div>
          <!-- 链接的title -->
          <div class="set-circle-link">
            <span class="base-tips">请输入链接标题</span>
            <el-input
              v-model="linkTitle"
              type="textarea"
              placeholder="请输入链接标题"
              maxlength="200"
              show-word-limit
              :autosize="{ minRows: 6, maxRows: 6 }"
              resize="none"
            ></el-input>
          </div>
          <!-- 链接的url -->
          <div class="set-circle-link">
            <span class="base-tips">请输入链接地址</span>
            <el-input
              v-model="linkUrl"
              placeholder="请输入链接地址"
              maxlength="200"
              minlength="12"
              clearable
            ></el-input>
          </div>
        </template>

        <!-- 评论窗口 -->
        <div class="set-circle-comment">
          <el-input
            v-if="addComment && showComentArea"
            v-model="comment"
            class="add-commnet-area"
            type="textarea"
            placeholder="如果有需要，请输入评论"
            maxlength="300"
            show-word-limit
            :autosize="{ minRows: 6, maxRows: 6 }"
            resize="none"
          ></el-input>
          <el-checkbox v-model="addComment" style="margin-right: 0" @change="addCommentChange">添加评论</el-checkbox>
          <p
            v-show="addComment"
            style="color: #ff9f00"
            @click="showComentArea = !showComentArea"
            v-text="showComentArea ? '收起' : '展开'"
          ></p>
        </div>
      </div>

      <!-- footer -->
      <span slot="footer">
        <el-input
          v-model="remarks"
          style="width: 570px; margin-left: 10px"
          clearable
          size="small"
          placeholder="请输入备注"
          maxlength="50"
          show-word-limit
        ></el-input>
        <el-button style="margin-left: 10px; color: #999999" size="small" @click="cancelFriendCircle">取 消</el-button>
        <el-button
          v-if="modifyRow.id"
          style="background-color: #ff9f00; border: solid #ff9f00 1px"
          type="primary"
          size="small"
          @click="createFriendCircle"
        >
          更 新
        </el-button>
        <el-button
          v-else
          style="background-color: #ff9f00; border: solid #ff9f00 1px"
          type="primary"
          size="small"
          @click="createFriendCircle"
        >
          创 建
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { resourcesList, addResources, updateResources, deleteResources } from '@/api/httpApi'
const imgError = require('@/assets/svg/conversation-image-error.svg')
import { fileUpload } from '@/utils/upload'
import Expression from '@/components/expression'

export default {
  name: 'MaterialLibrary',
  components: {
    Expression
  },
  data() {
    return {
      dataList: [], // 素材列表
      addGroupResource: false, // 创建群发素材
      addCircleResource: false, // 创建朋友圈素材
      pageSize: 20,
      currentPage: 1,
      totalNum: 0,
      remarks: '', // 备注
      modifyRow: {}, // 要更新的数据

      msgTypes: [
        {
          type: 'Text',
          icon: 'fa-file-text-o',
          name: '文本'
        },
        {
          type: 'Picture',
          icon: 'fa-file-image-o',
          name: '图片'
        },
        {
          type: 'Voice',
          icon: 'fa-microphone',
          name: '语音'
        },
        {
          type: 'Video',
          icon: 'fa-video-camera',
          name: '视频'
        },
        {
          type: 'Link',
          icon: 'fa-link',
          name: '链接'
        },
        {
          type: 'WeApp',
          icon: 'fa-product-hunt',
          name: '小程序'
        }
      ], // 消息类型
      msgType: 'Text', // 要群发的类型
      textContent: '', // 要群发的文本内容
      pictureUrl: '', // 要群发的图片url
      pictureName: '', // 要群发的图片名字
      voiceUrl: '', // 要群发的语音url
      voicePlayUrl: '', // 播放的语音
      voiceName: '', // 要群发的语音名字
      videoUrl: '', // 要群发的视频url
      videoName: '', // 要群发的视频名字
      weapp: {
        AppId: 'wxe99ba6e7fa3e8672',
        SourceName: 'gh_5b0c2f762fc0@app',
        Icon: 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5bBMPvk6Oohdlo4FpjGgLsTtcSYJKhibnoQWFphTVy7Bw/96',
        Source: '建业+',
        Title: '考拉之选 点断保鲜膜 食品级材质',
        Thumb:
          'http://gaia-projectc.oss-cn-hangzhou.aliyuncs.com/wxid_9988ti1oz81g22%2Fth_2fb4cbd7008c2e3cc33f6e49573c00cc.jpg',
        PagePath:
          'pages/index/index.html?_type=h5Link&h5url=https%3A%2F%2Fmall.yijiahn.com%2Fmall%2Fapp%2Fstatic%2Fgoods%2F3711147.html%3Fid%3D3711147&sharedUserId=2269485'
      }, // 小程序demo
      weappRules: {
        AppId: [{ required: true, message: '请输入AppId', trigger: 'blur' }],
        SourceName: [{ required: true, message: '请输入SourceName', trigger: 'blur' }],
        Icon: [{ required: true, message: '请输入Icon', trigger: 'blur' }],
        PagePath: [{ required: true, message: '请输入PagePath', trigger: 'blur' }],
        // Source: [
        //   { required: true, message: '请输入Source', trigger: 'blur' },
        // ],
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }]
      }, // 小程序表单验证
      linkForm: {
        Title: '“关闭领馆”落下帷幕! 外媒: 他们不再含泪抗议, 而是在大使馆前笑着合影',
        Thumb: 'http://www.jjldkj.com/files/phone/files/20200730/935FC7F27A771E914BD47DC261385309.jpg',
        Url: 'https://iflow.uc.cn/webview/news?app=meitullq-iflow&aid=17561738358438069514&cid=100&zzd_from=meitullq-iflow&uc_param_str=dndsfrvesvntnwpfgibicp&recoid=2043722754382504392&rd_type=reco&sp_gz=0&activity=1&activity2=1&dn=cf9807c357d1e8561c9aef3f75f05e71&enuid=AAPTn90AUlH8qpsGXMgpzgD%2BzWybOCOjkJX%2B2Ou9k8Lrzg%3D%3D&uc_iflow_biz=cmt%3A1&imei=bTkwAA3esoPsTi%2Ff%2FLrBSXG9zpdQ2YF7sw%3D%3D',
        Des: '震惊Des',
        TypeStr: '[链接]'
      }, // 链接demo
      linkRules: {
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }],
        Url: [{ required: true, message: '请输入Url', trigger: 'blur' }],
        Des: [{ required: true, message: '请输入Des', trigger: 'blur' }]
      }, // 链接表单验证
      tasktypeMap: {
        1: '群发素材',
        2: '朋友圈素材',
        3: '链接素材',
        4: '小程序素材',
        5: 'Emoji'
      }, // 任务类型
      restypeMap: {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13,
        Emoji: 14,
        1: '文本',
        2: '图片',
        3: '语音',
        4: '视频',
        6: '链接',
        13: '小程序',
        14: 'Emoji'
      }, // 消息类型
      linkName: {
        Title: '链接标题',
        Thumb: '图片网址',
        Url: '链接地址',
        Des: '链接描述'
      }, // 链接字段对应的中文

      circleType: 'text', // 朋友圈类型
      addComment: false, // 添加评论
      showComentArea: false, // 展示添加评论的text-area
      // textContent: '', // 文本
      comment: '', // 评论
      imageUrls: [], // 图片
      hideUpload: false, // 隐藏图片上传按钮
      showFileList: true, // 显示图片列表
      upData: { myfile: '', packageName: 'pc' }, // 上传文件data
      imagesList: [], // 图片回显
      imageUrl: '', // 大图url
      dialogVisible: false, // 显示大图
      videoUploading: false, // 视频上传中
      linkUrl: 'http://xiaohua.zol.com.cn/detail60/59426.html', // 链接地址
      linkImg: 'https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture', // 链接图片
      linkTitle: '看一看，乐一乐', // 链接标题
      circleTypeTip: {
        picture: '只能上传jpg/png文件，且不超过20MB',
        video: '只能上传mp4文件，且不超过10秒',
        link: ''
      } // 朋友圈类型提示
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      actionUrl: 'actionUrl'
    })
  },
  created() {
    // 查询日志
    this.queryResourceData()
  },
  methods: {
    // 查询素材
    queryResourceData() {
      resourcesList(this.currentUser.SupplierId, this.currentPage, this.pageSize).then((res) => {
        if (res.code === 0 && res.data.rows) {
          // const nl = res.data.rows.filter((x) => {
          //   return x.type !== 5
          // })
          const nc = res.data.rows.map((x) => {
            const jc = JSON.parse(x.content)
            jc.id = x.id
            jc.cid = x.cid
            jc.createTime = x.createTime
            jc.type = x.type
            jc.remarks = x.remarks
            return jc
          })
          console.log(nc)
          this.dataList = nc
          this.totalNum = res.data.records || 0
        } else {
          this.dataList = []
          this.totalNum = 0
        }
      })
    },
    // 切换群发的类型
    toggleGroupSendType(cType) {
      // 如果是编辑状态 不能更改type
      if (this.modifyRow.id) return
      this.msgType = cType
    },
    // 切换朋友圈类型
    toggleCircleType(cType) {
      // 如果是编辑状态 不能更改type
      if (this.modifyRow.id) return
      this.circleType = cType
    },
    // 取消创建群发
    cancleGroupSend() {
      this.modifyRow = {}
      this.addGroupResource = false
    },
    // 取消创建朋友圈素材
    cancelFriendCircle() {
      this.modifyRow = {}
      this.addCircleResource = false
    },
    // 创建群发素材
    createGroupSend() {
      let msgContent = this.textContent // 发送的内容 默认是文本内容
      if (this.msgType === 'Picture') {
        msgContent = this.pictureUrl
      } else if (this.msgType === 'Voice') {
        msgContent = this.voiceUrl
      } else if (this.msgType === 'Video') {
        msgContent = this.videoUrl
      } else if (this.msgType === 'Link') {
        msgContent = JSON.stringify(this.linkForm)
      } else if (this.msgType === 'WeApp') {
        msgContent = JSON.stringify(this.weapp)
      }
      // 发送的内容不能为空
      if (msgContent.length === 0) {
        this.$alert('内容不能为空！', '提示', { type: 'warning' })
        return
      }
      // restype
      const typeMap = {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13
      }
      const message = {
        restype: typeMap[this.msgType], // 资源类型
        content: msgContent // 内容
      }
      if (this.modifyRow.id) {
        updateResources(
          this.modifyRow.id,
          this.currentUser.SupplierId,
          this.modifyRow.type,
          JSON.stringify(message),
          this.remarks
        )
          .then((res) => {
            if (res.code === 0) {
              this.queryResourceData()
              this.cancleGroupSend()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      } else {
        addResources(this.currentUser.SupplierId, JSON.stringify(message), 1, this.remarks)
          .then((res) => {
            if (res.code === 0) {
              this.queryResourceData()
              this.cancleGroupSend()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      }
    },
    // 创建朋友圈素材
    createFriendCircle() {
      // 表单验证
      if (this.circleType === 'text' && !this.textContent) {
        this.$message.warning('请设置文本内容!')
        return
      } else if (this.circleType === 'picture' && this.imageUrls.length === 0) {
        this.$message.warning('请设置图片!')
        return
      } else if (this.circleType === 'video' && !this.videoUrl) {
        this.$message.warning('请设置视频!')
        return
      } else if (this.circleType === 'link' && (!this.linkUrl || !this.linkImg || !this.linkTitle)) {
        this.$message.warning('请设置链接参数!')
        return
      }
      // 附件
      let attachment = {}
      switch (this.circleType) {
        case 'picture':
          attachment = { Type: 2, Content: this.imageUrls }
          break
        case 'video':
          attachment = { Type: 3, Content: [this.videoUrl] }
          break
        case 'link':
          // 链接：[url;标题;图片url]
          attachment = { Type: 0, Content: [this.linkUrl, this.linkTitle, this.linkImg] }
          break
        default:
          break
      }
      const message = {
        circleType: this.circleType,
        imagesList: this.imagesList,
        content: this.textContent,
        comment: this.comment,
        attachment: attachment
      }
      if (this.modifyRow.id) {
        updateResources(this.modifyRow.id, this.currentUser.SupplierId, 2, JSON.stringify(message), this.remarks)
          .then((res) => {
            if (res.code === 0) {
              this.queryResourceData()
              this.addCircleResource = false
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      } else {
        addResources(this.currentUser.SupplierId, JSON.stringify(message), 2, this.remarks)
          .then((res) => {
            if (res.code === 0) {
              this.queryResourceData()
              this.addCircleResource = false
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      }
    },
    // 删除素材
    deleteItem(rid) {
      deleteResources(rid)
        .then((res) => {
          if (res.code === 0) {
            this.queryResourceData()
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 修改素材
    modifyItem(row) {
      this.modifyRow = row
      if (row.type === 2) {
        this.circleType = row.circleType
        if (row.circleType === 'picture') {
          this.imageUrls = row.attachment.Content
          this.imagesList = row.imagesList
        } else if (row.circleType === 'video') {
          this.videoUrl = row.attachment.Content
        } else if (row.circleType === 'link') {
          this.linkUrl = row.attachment.Content[0]
          this.linkTitle = row.attachment.Content[1]
          this.linkImg = row.attachment.Content[2]
        }
        if (row.content) {
          this.textContent = row.content
        }
        if (row.comment) {
          this.addComment = true
          this.comment = row.comment
        }
        this.remarks = row.remarks
        this.addCircleResource = true
      } else {
        if (row.restype === 1) {
          this.msgType = 'Text'
          this.textContent = row.content // 发送的内容 默认是文本内容
        } else if (row.restype === 2) {
          this.msgType = 'Picture'
          this.pictureUrl = row.content
        } else if (row.restype === 3) {
          this.msgType = 'Voice'
          this.voiceUrl = row.content
        } else if (row.restype === 4) {
          this.msgType = 'Video'
          this.videoUrl = row.content
        } else if (row.restype === 6) {
          this.msgType = 'Link'
          this.linkForm = JSON.parse(row.content)
        } else if (row.restype === 13) {
          this.msgType = 'WeApp'
          this.weapp = JSON.parse(row.content)
        }
        this.remarks = row.remarks
        this.addGroupResource = true
      }
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryResourceData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryResourceData()
    },
    // 解析内容
    decodeChat(chat) {
      const content = chat.content
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let thumb = ''
      let str = ''
      if (chat.type === 2) {
        // 文本
        if (chat.content) {
          str = `<p style="padding:5px;">${chat.content}</p>`
        }
        // 附件
        if (chat.circleType === 'picture') {
          for (const imgUrl of chat.attachment.Content) {
            str = str + `<img style="width:80px;" src="${imgUrl}"  alt="图片"/>`
          }
        } else if (chat.circleType === 'video') {
          str =
            str +
            `<video class="video-box" src="${chat.attachment.Content[0]}" type="video/mp4" alt="视频" controls></video>`
        } else if (chat.circleType === 'link') {
          //  [this.linkUrl, this.linkTitle, this.linkImg]
          str =
            str +
            `<a href="${chat.attachment.Content[0]}" target="_blank">
          <p style="padding:5px;">${chat.attachment.Content[1]}</p>
          </a>`
          // <img style="width:80px;" src="${chat.attachment.Content[2]}"  alt="图片"/>
        }
        // 评论
        if (chat.comment) {
          str = str + `<p>${chat.comment}</p>`
        }
        return str
      } else {
        switch (chat.restype) {
          // 文本 1
          case 'Text':
          case 1:
            return content
          // 图片 2
          case 'Picture':
          case 2:
            return `<img class="chat-img" src="${content}"  alt="图片"/>`
          // 语音 3
          case 'Voice':
          case 3:
            if (content.endsWith('.amr')) {
              thumb = content.replace(/.amr$/, '.mp3')
            } else {
              thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
            }
            return `<audio src="${thumb}" alt="语音" controls></audio>`
          // 视频 4
          case 'Video':
          case 4:
            return `<video class="video-box" src="${content}" type="video/mp4" alt="视频" controls></video>`
          // 链接消息 6
          case 'Link':
          case 6:
            str = `
                    <span class="link-title">${jContent.Title}</span>
                    <div class="link-content">
                      <span class="link-des">${jContent.Des}</span>
                      <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                    </div>
                    <div class="link-type">${jContent.TypeStr}</div>
                    `
            return str
          // 小程序 13
          case 'WeApp':
          case 13: {
            let appIcon = imgError
            let appSource = '无效小程序'
            let appTitle = '无效小程序'
            let appThumb = ''
            let appTypeStr = '小程序'
            if (typeof content === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
              appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
              appSource = jContent.Source
              appTitle = jContent.Title || jContent.Des
              appThumb = jContent.Thumb
              appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
            }

            str = `
              <div class="app-des">
              <img class="app-icon" src="${appIcon}" alt="icon" />
              <span class="app-source ellipsis">${appSource}</span>
              </div>
              <div class="app-title ellipsis">${appTitle}</div>
              <img class="app-img" src="${appThumb}" />
              <div class="app-typestr">${appTypeStr}</div>
               `
            return str
            // return jContent
          }
          case 'Emoji':
          case 14: {
            const eMap = {
              'jsb_j.png': 'http://emoji.qpic.cn/wx_emoji/abG5b87mcOW7YxBZFZPZOBXUjE99n48g6Znn6zaUiaVRtxMBYaEEKoA/',
              'jsb_s.png': 'http://emoji.qpic.cn/wx_emoji/ARQOAfC52Cu6iczyCvLhibUNQxCialTeaeObDoEMsL7uJjyV5dqzCNCFQ/',
              'jsb_b.png': 'http://emoji.qpic.cn/wx_emoji/Ty7jp6YeVib7MibicS8eb9buorVCg7mYTFXxuEpVDyQMaqK6PUoOcGxbQ/',
              'dice_1.png': 'http://emoji.qpic.cn/wx_emoji/QsDXJwBwXEXGFwLHJCm6haBlFls30vzPQcZTib9dyhLiazKxoPX6kp0A/',
              'dice_2.png':
                'http://emoji.qpic.cn/wx_emoji/YbCHM38dRYCIWbKmiaBrdnPrfuuwicLD2iacSWaPoAiaFrUySG87ELibOXQ/',
              'dice_3.png': 'http://emoji.qpic.cn/wx_emoji/lgVbvPFtzP8ytMiaKZMUoV3BXNPRfUaP69vozHfNarmX3MlTrgOhrkA/',
              'dice_4.png': 'http://emoji.qpic.cn/wx_emoji/zaBCJf5hVDn8NlibdrxV4NoPc12d28S7s67UCJqwynRmB0spdttIbeQ/',
              'dice_5.png': 'http://emoji.qpic.cn/wx_emoji/72IJJTdBzuibcxvnpFVicUAzCWRJC3cKhtkpMHTFejC2cyOeEGSHibTKw/',
              'dice_6.png': 'http://emoji.qpic.cn/wx_emoji/Jowow1icuI3XqtkFeQgIuzjIEYHdtJZictGFJjTsAFwW1g6cx1uTaQfw/'
            }
            thumb = content.Thumb || content.cdnUrl
            if (thumb) {
              if (eMap[thumb]) {
                return `<img class="chat-img" src="${eMap[thumb]}" title="点击看大图" alt="图片"/>`
              }
              return `<img class="chat-img" src="${thumb}" title="点击看大图" alt="图片"/>`
            }
            return content
          }
          // 不支持的消息
          default:
            return `不支持的消息类型${chat.ContentType}`
        }
      }
    },
    // 选择图片
    chosePicture() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.pictureInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        // image/jpeg
        const isImage = file.type.indexOf('image') >= 0
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20

        if (!isImage) {
          this.$alert('图片格式不对！', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传图片大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.pictureName = file.name // 文件名
            this.pictureUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deletePicture() {
      this.pictureName = ''
      this.pictureUrl = ''
    },
    // 选择图片
    choseVideo() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.videoInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const isMP4 = file.type === 'video/mp4'
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20
        if (!isMP4) {
          this.$alert('上传视频只能是 MP4 格式!', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传视频大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.videoName = file.name // 文件名
            this.videoUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deleteVideo() {
      this.videoUrl = ''
      this.videoName = ''
    },
    // 选择语音
    choseVoice() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.voiceInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const fileSize = file.size
        const fileName = file.name
        const fileType = fileName.replace(/.+\./, '').toLowerCase()
        // 文件大于10M不能发送
        if (fileSize > 104857600 || fileSize <= 0) {
          this.$alert('语音大小不能超过 10MB!', '提示', { type: 'warning' })
          return
        }
        // 验证文件类型
        if (['amr', 'mp3'].indexOf(fileType) < 0) {
          this.$alert('语音格式不对!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)

        // 如果选择的是mp3文件，文件上传到服务器，转为amr，返回amr的地址
        // 如果选择的是amr文件，直接上传到服务器，返回amr的地址
        if (fileType === 'mp3') {
          formdata.append('isMp3ToAmr', true)
        } else if (fileType === 'amr') {
          formdata.append('isAmrToMp3', false)
        }

        // 上传mp3 或者amr转为MP3
        const formDataMp3 = new FormData()
        formDataMp3.append('myfile', fileObj[0])
        if (fileType === 'mp3') {
          formDataMp3.append('isMp3ToAmr', false)
        } else if (fileType === 'amr') {
          formDataMp3.append('isAmrToMp3', true)
        }
        fileUpload(formDataMp3)
          .then((res) => {
            setTimeout(() => {
              this.voicePlayUrl = res.data.url
            }, 2000)
          })
          .catch((err) => {
            this.$message.error(err)
          })

        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.voiceName = file.name // 文件名
            this.voiceUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除语音
    deleteVoice() {
      this.voiceUrl = ''
      this.voiceName = ''
    },
    // 展示/隐藏评论框
    addCommentChange(val) {
      this.showComentArea = !!val
    },
    // 图片超出个数限制时的钩子
    handleImageExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 图片改变
    handleImageChange(file, fileList) {
      if (fileList.length === 9) {
        this.showFileList = true
        this.hideUpload = true
      }
    },
    // 图片类型大小验证
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.warning('上传图片只能是 JPG|PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.warning('上传图片大小不能超过 5MB!')
      }
      this.upData.myfile = file
      return isJPG && isLt2M
    },
    // 图片上传成功
    handleImageSuccess(res, file, fileList) {
      for (const fl of fileList) {
        if (fl.response) {
          fl.url = fl.response.data.url
        }
      }
      this.imagesList = fileList
      this.imageUrls.push(res.data.url)
    },
    // 图片上传失败
    handleImageError(err) {
      this.$alert(err, '文件上传失败', { type: 'error' })
      this.hideUpload = false
    },
    // 图片移除
    handleImageRemove(file, fileList) {
      const imgUrlId = this.imageUrls.indexOf(file.response.data.url)
      this.imageUrls.splice(imgUrlId, 1)
      this.hideUpload = false
      this.imagesList = fileList
    },
    // 添加视频
    choseCircleVideo() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.videoInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const isMP4 = file.type === 'video/mp4'
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20
        if (!isMP4) {
          this.$alert('上传视频只能是 MP4 格式!', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传视频大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.videoName = file.name // 文件名
            this.videoUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除视频
    deleteCircleVideo() {
      this.videoUrl = ''
      this.videoName = ''
    },
    // 图片|视频 大图展示
    handlePictureCardPreview(file) {
      if (this.circleType === 'picture') {
        this.imageUrl = file.url
      } else {
        this.videoUrl = file.url
      }
      this.dialogVisible = true
    },
    // 添加表情
    modifyContent(rm) {
      this.textContent = this.textContent + rm
    }
  }
}
</script>

<style lang="scss" scoped>
.material-libary {
  height: 100%;
  width: 100%;
  padding: 0 20px;
  overflow: hidden;
  display: flex;
  align-items: center;
  flex-direction: column;
  ::v-deep .chat-link {
    flex-direction: column;
    width: 300px;
    max-width: 100%;
    cursor: pointer;
    .link-title {
      font-size: 14px;
      font-weight: 600;
    }
    .link-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .link-des {
        flex: auto;
        color: #aaaaaa;
        font-size: 10px;
        margin-right: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        word-wrap: break-word;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
      }
      .link-img {
        max-width: 50px;
        max-height: 50px;
        min-height: 50px;
        min-width: 50px;
        border-radius: 5px;
      }
    }
    .link-type {
      color: #aaaaaa;
      margin-top: 5px;
      text-align: start;
      border-top: solid #e8eaec 1px;
    }
  }
  ::v-deep .chat-app {
    width: 300px;
    max-width: 100%;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    .app-des {
      display: flex;
      .app-icon {
        width: 20px;
        height: 20px;
      }
      .app-source {
        width: 100%;
        font-size: 12px;
        margin-left: 5px;
        color: gray;
      }
    }
    .app-title {
      width: 100%;
      height: 30px;
      font-size: 12px;
      font-weight: 600;
      line-height: 30px;
    }
    .app-img {
      align-self: center;
      max-width: 200px;
    }
    .app-typestr {
      height: 25px;
      margin-top: 5px;
      line-height: 25px;
      color: gray;
      text-align: start;
      border-top: solid #aaaaaa 1px;
    }
  }
  ::v-deep .chat-img {
    width: 100px;
    cursor: pointer;
  }
}
.set-circle-type {
  display: flex;
  padding: 0 10px;
  .circle-type-item {
    width: 80px;
    font-size: 14px;
    color: #333333;
    padding: 5px 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }
  .circle-type-item-select {
    color: #ff9f00;
    background-color: #fff7e8;
    border-radius: 15px;
  }
  .circle-log {
    position: absolute;
    right: 10px;
    top: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}

.set-send-content {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  // margin: 10px;
  padding: 10px;
  overflow: auto;

  .set-circle-link {
    display: flex;
    align-items: center;
  }

  .add-pictures {
    position: relative;
    height: 240px;
    ::v-deep .set-image-ulrs {
      width: 100%;
      // border: solid blue 1px;
      .el-upload--picture-card {
        width: 110px;
        height: 110px;
        line-height: 110px;
      }
      .el-upload-list__item {
        width: 110px;
        height: 110px;
      }
    }
    ::v-deep .hide .el-upload--picture-card {
      display: none;
    }
  }

  .add-video {
    height: 240px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .add-video-label {
      cursor: pointer;
    }
    video {
      height: 210px;
      width: auto;
    }
    .video-name-delete {
      display: flex;
      align-items: center;
      height: 30px;
      min-height: 30px;
      i {
        cursor: pointer;
      }
    }
  }

  .qq-expression {
    padding: 2px;
    position: absolute;
    left: 10px;
    top: 216px;
  }

  ::v-deep .set-circle-link {
    .el-input--suffix {
      width: 50%;
    }
    .el-textarea {
      width: 50%;
    }
  }

  .set-circle-comment {
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;
    position: relative;
    p {
      margin-left: 10px;
      cursor: pointer;
    }

    ::v-deep .add-commnet-area {
      position: absolute;
      bottom: 32px;
      .el-textarea__inner {
        background-color: #fdfdfd;
      }
    }
  }
}
.qq-expression-2 {
  padding: 2px;
  position: absolute;
  left: 100px;
  top: 250px;
}
</style>
